package com.zhangfb95.crosschain.console.command;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zhangfb95.crosschain.console.enums.CommandEnum;
import com.zhangfb95.crosschain.console.enums.KeyStoreTypeEnum;
import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.infra.util.Base64Util;
import com.zhangfb95.crosschain.infra.util.FileUtil;
import com.zhangfb95.crosschain.infra.util.json.JsonUtil;
import com.zhangfb95.crosschain.sdk.CrossChainClient;
import com.zhangfb95.crosschain.sdk.infra.model.api.request.server.rpcchainaccount.RpcChainAccountAddApiReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangfubing
 * @since 2023/12/21
 */
@Component
public class AddChainAccountCommand implements Command {

    @Autowired
    private CrossChainClient crossChainClient;
    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public CommandEnum command() {
        return CommandEnum.ADD_CHAIN_ACCOUNT;
    }

    @Override
    public boolean handle(String[] args) {
        if (args.length < 2 || isHelp(args)) {
            printHelpInfo();
            return false;
        }

        String keyStoreType = args[0];
        String data = args[1];
        RpcChainAccountAddApiReq apiReq = jsonUtil.readValue(data, new TypeReference<>() {
        });
        if (KeyStoreTypeEnum.BASE64.is(keyStoreType)) {
            apiReq.setPrivateKey(Base64Util.decodeToString(apiReq.getPrivateKey()));
            apiReq.setPublicKey(Base64Util.decodeToString(apiReq.getPublicKey()));
        } else if (KeyStoreTypeEnum.FILE.is(keyStoreType)) {
            apiReq.setPrivateKey(FileUtil.readContent(apiReq.getPrivateKey()));
            apiReq.setPublicKey(FileUtil.readContent(apiReq.getPublicKey()));
        } else {
            System.out.println("Result: unsupported keyStoreType, current support: base64, file.");
            return false;
        }

        Result<Void> apiRes = crossChainClient.addChainAccount(apiReq);
        if (apiRes.isSuccess()) {
            System.out.println("Result: success");
        } else {
            System.out.println("Result: " + apiRes.getMsg());
        }
        return false;
    }

    private void printHelpInfo() {
        System.out.println("Usage: addChainAccount [keyStoreType] [data]");
        System.out.println("keyStoreType: base64, file");
        RpcChainAccountAddApiReq sampleApiReq = new RpcChainAccountAddApiReq();
        Map<String, String> properties = new HashMap<>();
        properties.put("key1", "value1");
        sampleApiReq.setProperties(properties);
        System.out.println("data: " + jsonUtil.toJsonQuietly(sampleApiReq));
    }
}
